package jdos;

import jdos.cpu.*;
import jdos.cpu.Callback.Handler;
import jdos.debug.Debug;
import jdos.gui.Main;
import jdos.hardware.*;
import jdos.hardware.VGA;
import jdos.ints.*;
import jdos.misc.Log;
import jdos.misc.setup.*;

public class Dosbox {
	static public boolean allPrivileges = true;

	public static final boolean applet = false;

	private static /*Bit32u*/long ticksRemain;
	private static /*Bit32u*/long ticksLast;
	private static /*Bit32u*/long ticksAdded;
	public static /*Bit32s*/int ticksDone;
	public static /*Bit32u*/long ticksScheduled;
	public static final boolean ticksLocked = false;

	public static /*Bitu*/int Normal_Loop() {
		/*Bits*/int ret;
		while (true) {
			if (Pic.PIC_RunQueue()) {
				ret = Core_full.CPU_Core_Normal_Run.call();
				if (ret < 0) return 1;
				if (ret > 0) {
						//                            if (ret != 15 && ret !=7 && ret != 19 && ret != 16)
						//                               System.out.println(Callback.CallBack_Handlers[ret].getName());
						Handler h = Callback.CallBack_Handlers[ret];
						/*Bitu*/int blah = h.call();
						if (blah != 0) return blah;

				}
				if (Config.C_DEBUG) if (Debug.DEBUG_ExitLoop()) return 0;
			} else {
				Main.GFX_Events();
				if (ticksRemain > 0) {
					Timer.TIMER_AddTick();
					ticksRemain--;
				} else {
					//goto increaseticks;
					break;
				}
			}
		}
		//increaseticks:
		if (ticksLocked) {
			ticksRemain = 5;
			/* Reset any auto cycle guessing for this frame */
			ticksLast = Main.GetTicks();
			ticksAdded = 0;
			ticksDone = 0;
			ticksScheduled = 0;
		} else {
			/*Bit32u*/long ticksNew;
			ticksNew = Main.GetTicks();
			ticksScheduled += ticksAdded;
			if (ticksNew > ticksLast) {
				ticksRemain = ticksNew - ticksLast;
				ticksLast = ticksNew;
				ticksDone += ticksRemain;
				if (ticksRemain > 20) {
					ticksRemain = 20;
				}
				ticksAdded = ticksRemain;

			} else {
				ticksAdded = 0;
				Main.Delay(1);
				ticksDone -= Main.GetTicks() - ticksNew;
				if (ticksDone < 0) ticksDone = 0;
			}
		}
		return 0;
	}

	static public void DOSBOX_RunMachine() {
		/*Bitu*/int ret;
		do {
				ret = Normal_Loop();
		} while (ret == 0);
	}


	public static void DOSBOX_RealInit() {
		System.out.println("DOSBOX_RealInit");
		/* Initialize some dosbox internals */

		ticksRemain = 0;
		ticksLast = Main.GetTicks();

		Int10.int10 = new Int10.Int10Data();
		VGA.VGA_Init2();
	}
}
